package dept

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SubListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptSubListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubListLogic {
	return &SubListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SubListLogic) DeptSubList(in *pb.DeptListReq) (*pb.DeptListResp, error) {
	// 1.查询部门信息
	deptMapper := mapper.NewDeptMapper()
	dbEngin := l.svcCtx.DBEngin
	deptEntity, err := deptMapper.SelectOneForParentName(dbEngin, in.DeptId)
	if err != nil {
		return nil, err
	}
	if deptEntity.DeptId < 1 {
		return nil, excption.NewErrCode(constans.DeptNoExistError)
	}

	// 递归查询子节点
	mainResp := new(pb.DeptListResp)
	mainResp.DeptId = deptEntity.DeptId
	mainResp.Name = deptEntity.Name
	mainResp.ParentId = deptEntity.ParentId
	mainResp.ParentName = deptEntity.ParentName
	mainResp.OrderNum = int32(deptEntity.OrderNum)
	err2 := l.looperSubDeptList(mainResp, in.DeptId, deptMapper)
	if err2 != nil {
		return nil, err2
	}
	// 封装返回信息
	return mainResp, nil
}

func (l *SubListLogic) looperSubDeptList(resp *pb.DeptListResp, deptId int64, deptMapper *mapper.DeptMapper) error {
	queryBo := bo.SysDeptBO{
		ParentId:   deptId,
		HasDelFlag: true,
		DelFlag:    0,
	}
	selectList, err := deptMapper.SelectList(l.svcCtx.DBEngin, queryBo)
	if err != nil {
		return err
	}
	if len(selectList) < 1 {
		return nil
	}
	var subList []*pb.DeptListResp
	for _, v := range selectList {
		subResp := new(pb.DeptListResp)
		subResp.DeptId = v.DeptId
		subResp.Name = v.Name
		subResp.ParentId = v.ParentId
		subResp.OrderNum = int32(v.OrderNum)
		subResp.ParentName = resp.Name
		lopperErr := l.looperSubDeptList(subResp, v.DeptId, deptMapper)
		if lopperErr != nil {
			return nil
		}
		subList = append(subList, subResp)
	}
	resp.SubList = subList
	return nil
}
